//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package project_draw_dao

import (
	"context"

	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

type ContentDbItem struct {
	DrawId  string `bson:"_id"`
	Content string `bson:"content"`
}

type _ContentDao struct {
	mc *mongo.Collection
}

func newContentDao(db *mongo.Database) (*_ContentDao, error) {
	mc := db.Collection(db_ns.DB_NS_PROJECT_DRAW + "content")
	return &_ContentDao{mc: mc}, nil
}

func (db *_ContentDao) Insert(ctx context.Context, dbItem *ContentDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_ContentDao) Update(ctx context.Context, drawId, content string) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": drawId}, bson.M{"$set": bson.M{"content": content}})
	return err
}

func (db *_ContentDao) Exist(ctx context.Context, drawId string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": drawId})
	return count > 0, err
}

func (db *_ContentDao) Get(ctx context.Context, drawId string) (*ContentDbItem, error) {
	retItem := &ContentDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": drawId}).Decode(retItem)
	return retItem, err
}

func (db *_ContentDao) ListById(ctx context.Context, drawIdList []string) ([]*ContentDbItem, error) {
	if len(drawIdList) == 0 {
		return []*ContentDbItem{}, nil
	}
	cursor, err := db.mc.Find(ctx, bson.M{"_id": bson.M{"$in": drawIdList}})
	if err != nil {
		return nil, err
	}
	retList := []*ContentDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_ContentDao) Remove(ctx context.Context, drawId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": drawId})
	return err
}
